package com.qyhl.webtv.module_broke.scoop.detail;

import android.Manifest;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.request.RequestOptions;
import com.example.sdk.statisticssdk.StatisticsMainInit;
import com.gyf.immersionbar.ImmersionBar;
import com.like.LikeButton;
import com.like.OnLikeListener;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.MPermissionUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.ScoopListBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_broke.R;
import com.qyhl.webtv.module_broke.R2;
import com.qyhl.webtv.module_broke.utils.radiobutton.MediaManager;
import com.qyhl.webtv.module_broke.utils.radiobutton.ScoopButton;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.abslistview.CommonAdapter;
import com.zhy.adapter.abslistview.ViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoCover;
import static com.qyhl.webtv.commonlib.utils.view.video.emptyvideo.EmptyControlVideoActivity.IntentKey_VideoUrl;


/**
 * Created by qyhl on 2017/12/12.
 * 内容详情
 */

@Route(path = ARouterPathConstant.SCOOP_DETAIL_ACTIVIT)
public class ScoopDetailActivity extends BaseActivity implements ScoopDetailContract.ScoopDetailView {
    @BindView(R2.id.share_btn)
    ImageView shareBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.listView)
    ListView listView;
    @BindView(R2.id.layout_mask)
    LoadingLayout layoutMask;
    @BindView(R2.id.back_btn)
    ImageView backBtn;
    @BindView(R2.id.scp_detail)
    RelativeLayout scpTitle;

    private ScoopDetailPresenter mPresenter;

    TextView mTitle;
    TextView author;
    TextView publishDate;
    TextView attentionNum;
    RelativeLayout tagLayout;
    TextView summary;
    RelativeLayout videoLayout;
    ScoopButton radioBtn;
    RelativeLayout typeLayout;
    TextView location;
    ImageView stateIcon, videoCover;
    TextView stateText;
    LinearLayout resultLayout;
    LinearLayout photoLayout;
    LikeButton likeButton;

    @Autowired(name = "id")
    String brokeId;

    private ScoopButton myVoiceButton;
    private String text;


    private int follows;//关注数

    private ScoopListBean mBean;

    private RequestOptions options;


    private boolean likeButtonEnable = true;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getContentView() {
        return R.layout.broke_activity_scoop_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ScoopDetailPresenter(this);
        initView();
        mPresenter.getDetail(brokeId + "");
    }

    @Override
    protected void setListener() {
        setListeners();
    }

    /**
     * 初始化
     */
    private void initView() {
        layoutMask.setStatus(LoadingLayout.Loading);
        if (CommonUtils.getInstance().getSite() == 174) {
            title.setText("");
        } else {
            title.setText("");
        }


        BusFactory.getBus().register(this);

        //设置header
        View view = LayoutInflater.from(this).inflate(R.layout.broke_header_scoop_detail, null);
        mTitle = (TextView) view.findViewById(R.id.title);
        author = (TextView) view.findViewById(R.id.author);
        publishDate = (TextView) view.findViewById(R.id.publish_date);
        attentionNum = (TextView) view.findViewById(R.id.attention_num);
        tagLayout = (RelativeLayout) view.findViewById(R.id.tag_layout);
        summary = (TextView) view.findViewById(R.id.summary);
        videoLayout = (RelativeLayout) view.findViewById(R.id.video_layout);
        videoCover = (ImageView) view.findViewById(R.id.video_cover);
        radioBtn = (ScoopButton) view.findViewById(R.id.radio_btn);
        typeLayout = (RelativeLayout) view.findViewById(R.id.type_layout);
        location = (TextView) view.findViewById(R.id.location);
        stateIcon = (ImageView) view.findViewById(R.id.state_icon);
        stateText = (TextView) view.findViewById(R.id.state_text);
        resultLayout = (LinearLayout) view.findViewById(R.id.result_layout);
        photoLayout = (LinearLayout) view.findViewById(R.id.photo_layout);
        likeButton = (LikeButton) view.findViewById(R.id.like_btn);

        options = new RequestOptions()
                .placeholder(R.drawable.cover_large_default)
                .error(R.drawable.cover_large_default)
                .priority(Priority.HIGH);

        listView.addHeaderView(view);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //重载
        layoutMask.setOnReloadListener(v -> {
            layoutMask.setReloadButtonText("加载中...");
            mPresenter.getDetail(brokeId + "");
        });

        //分享
        shareBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MPermissionUtils.requestPermissionsResult(ScoopDetailActivity.this, 1, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, new MPermissionUtils.OnPermissionListener() {
                    @Override
                    public void onPermissionGranted() {
                        if (mBean != null) {
                            MShareBoard shareBoard = new MShareBoard(ScoopDetailActivity.this, brokeId + "", mBean.getBrokeNews().getTitle(), mBean.getBrokeNews().getCoverImgUrl(), mBean.getBrokeNews().getContent(), CommonUtils.getInstance().getBannerId(), 9);
                            shareBoard.showPopupWindow();
//                            ShareUtils.getInstance().goShare(brokeId + "", 9, mBean.getBrokeNews().getContent(), mBean.getBrokeNews().getTitle(), mBean.getBrokeNews().getCoverImgUrl(), ScoopDetailActivity.this);
                        } else {
                            Toasty.normal(ScoopDetailActivity.this, "分享内容读取失败，稍后再试！").show();
                        }

                    }

                    @Override
                    public void onPermissionDenied() {
                        MPermissionUtils.showTipsDialog(ScoopDetailActivity.this);
                    }
                });
            }
        });

        //点赞
        likeButton.setOnLikeListener(new OnLikeListener() {
            @Override
            public void liked(final LikeButton likeButton) {
                if (likeButtonEnable) {
                    likeButtonEnable = false;
                    CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                        @Override
                        public void login(boolean isLogin) {
                            if (isLogin) {
                                likeButton.setEnabled(false);
                                mPresenter.addAttention(brokeId + "");
                            } else {
                                likeButton.setLiked(false);
                                Toasty.normal(ScoopDetailActivity.this, "尚未登录或登录已失效！").show();
                                RouterManager.routerLogin(ScoopDetailActivity.this, 0);
                                likeButtonEnable = true;
                            }
                        }

                        @Override
                        public void error(String s) {
                            likeButtonEnable = true;
                        }
                    });

                }
            }

            @Override
            public void unLiked(final LikeButton likeButton) {
                {
                    if (likeButtonEnable) {
                        likeButtonEnable = false;
                        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    likeButton.setEnabled(false);
                                    mPresenter.cancelAttention(brokeId + "");
                                } else {
                                    likeButton.setLiked(true);
                                    Toasty.normal(ScoopDetailActivity.this, "尚未登录或登录已失效！").show();
                                    RouterManager.routerLogin(ScoopDetailActivity.this, 0);
                                    likeButtonEnable = true;
                                }
                            }

                            @Override
                            public void error(String s) {
                                likeButtonEnable = true;
                            }
                        });

                    }
                }
            }
        });

        backBtn.setOnClickListener(v -> finish());


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 设置数据
     *
     * @param bean
     */
    @Override
    public void setDetail(ScoopListBean bean) {
        layoutMask.setReloadButtonText("点击重试~~");
        layoutMask.setStatus(LoadingLayout.Success);
        mBean = bean;

        //四川融媒统计
        if ((CommonUtils.getInstance().getSite() == 148 || CommonUtils.getInstance().getSite() == 145)) {
            StatisticsMainInit.reportLog(CommonUtils.getInstance().getUserName(), mBean.getBrokeNews().getId() + "", mBean.getBrokeNews().getTitle());
        }

        //设置标题
        if (StringUtils.isEmpty(mBean.getBrokeNews().getTitle())) {
            mTitle.setVisibility(View.GONE);
        } else {
            mTitle.setVisibility(View.VISIBLE);
            mTitle.setText(mBean.getBrokeNews().getTitle());//设置标题
        }

        if (mBean.getBrokeNews().getIsAnonymous() == 0) {
            author.setText("报料人：匿名用户");//设置内容人
        } else {
            author.setText("报料人：" + mBean.getBrokeNews().getAuthor());//设置内容人
        }

        publishDate.setText(DateUtils.detailDateTranslate(mBean.getBrokeNews().getPublishtime()));//设置发布时间

        follows = mBean.getAttention();
        if (bean.getIsAttention() == 0) {//初始化关注状态
            setNormal(follows);
        } else {
            setChecked(follows);
        }

        if (StringUtils.isEmpty(mBean.getBrokeNews().getContent())) {
            summary.setVisibility(View.GONE);
        } else {
            summary.setVisibility(View.VISIBLE);
            summary.setText(mBean.getBrokeNews().getContent());//设置描述
        }


        //地址
        if (StringUtils.isEmpty(mBean.getBrokeNews().getAddress())) {
            location.setVisibility(View.GONE);
        } else {
            location.setVisibility(View.VISIBLE);
            location.setText(mBean.getBrokeNews().getAddress());
        }

        //设置处理状态
        switch (mBean.getBrokeNews().getStatus()) {
            case 2://未处理
                stateIcon.setVisibility(View.GONE);
                stateText.setVisibility(View.GONE);
                break;
            case 21://处理中
                stateIcon.setVisibility(View.VISIBLE);
                stateText.setVisibility(View.VISIBLE);
                stateText.setText("处理中");
                stateText.setTextColor(getResources().getColor(R.color.global_base));
                stateIcon.setImageResource(R.drawable.scoop_disposing);
                break;
            case 22://已处理
                stateIcon.setVisibility(View.VISIBLE);
                stateText.setVisibility(View.VISIBLE);
                stateText.setText("已处理");
                stateText.setTextColor(getResources().getColor(R.color.scoop_disposed));
                stateIcon.setImageResource(R.drawable.scoop_disposed);
                break;
            case 23:
                stateIcon.setVisibility(View.GONE);
                stateText.setVisibility(View.GONE);
                break;
            default:
                break;
        }

        if (mBean.getTrackRecords() != null && mBean.getTrackRecords().size() != 0) {
            resultLayout.setVisibility(View.VISIBLE);
        } else {
            resultLayout.setVisibility(View.GONE);
        }

        listView.setAdapter(new CommonAdapter<ScoopListBean.TrackRecords>(this, R.layout.broke_item_scoop_detail, mBean.getTrackRecords()) {
            @Override
            protected void convert(ViewHolder holder, ScoopListBean.TrackRecords item, int position) {
                TextView reply = holder.getView(R.id.reply);
                reply.setText("您好，" + item.getTrackRecord().author + "回复：");
                reply.setVisibility(View.GONE);

                TextView replyContent = holder.getView(R.id.reply_content);
                replyContent.setText(item.getTrackRecord().getContent());

                TextView replyDate = holder.getView(R.id.reply_date);
                replyDate.setText(DateUtils.mTranslateDate(item.getTrackRecord().getCreatetime()));

                final LinearLayout imageLayout = holder.getView(R.id.result_image);
                imageLayout.removeAllViewsInLayout();
                if (item.getImages() == null || item.getImages().size() == 0) {
                    imageLayout.setVisibility(View.GONE);
                } else {
                    imageLayout.setVisibility(View.VISIBLE);
                    for (int i = 0; i < item.getImages().size(); i++) {
                        final ImageView imageView = new ImageView(ScoopDetailActivity.this);
                        final LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        param.setMargins(0, 0, 0, 10);
                        imageLayout.addView(imageView, param);
                        Glide.with(ScoopDetailActivity.this)
                                .load(item.getImages().get(i).getUrl())
                                .apply(options)
                                .into(imageView);
                    }
                }

            }
        });

        //判断显示类型
        switch (mBean.getBrokeNews().getType()) {
            case 0://图文
                videoLayout.setVisibility(View.GONE);
                radioBtn.setVisibility(View.GONE);

                if (mBean.getImages() == null || mBean.getImages().size() == 0) {
                    photoLayout.setVisibility(View.GONE);
                } else {
                    photoLayout.setVisibility(View.VISIBLE);
                    photoLayout.removeAllViewsInLayout();
                    for (int i = 0; i < mBean.getImages().size(); i++) {
                        final ImageView imageView = new ImageView(this);
                        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                        param.setMargins(0, 10, 0, 0);
                        photoLayout.addView(imageView, param);
                        Glide.with(this)
                                .load(mBean.getImages().get(i).getUrl())
                                .apply(options)
                                .into(imageView);
                    }
                }

                break;
            case 1://视频
                photoLayout.setVisibility(View.GONE);
                videoLayout.setVisibility(View.VISIBLE);
                radioBtn.setVisibility(View.GONE);
                ViewGroup.LayoutParams params = videoCover.getLayoutParams();
                if (bean.getVideoCoverWidth() > bean.getVideoCoverHeight()) {
                    params.width = (bean.getVideoCoverWidth() > 600 || bean.getVideoCoverWidth() <= 0) ? 600 : bean.getVideoCoverWidth();
                    params.height = params.width * 9 / 16;
                } else {
                    params.height = (bean.getVideoCoverHeight() > 600 || bean.getVideoCoverHeight() <= 0) ? 600 : bean.getVideoCoverHeight();
                    params.width = params.height * 9 / 16;
                }
                videoCover.setLayoutParams(params);

                Glide.with(this).load(mBean.getBrokeNews().getCoverImgUrl()).apply(new RequestOptions().error(R.drawable.cover_video_default).placeholder(R.drawable.cover_video_default)).into(videoCover);

                videoCover.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Bundle bundle = new Bundle();
                        bundle.putString(IntentKey_VideoUrl, bean.getBrokeNews().getUrl());
                        bundle.putString(IntentKey_VideoCover, bean.getBrokeNews().getCoverImgUrl());
                        RouterManager.router(ARouterPathConstant.VIDEO_EMPTY_CONTROL, bundle);
                    }
                });
                break;
            case 2://音频
                photoLayout.setVisibility(View.GONE);
                videoLayout.setVisibility(View.GONE);
                radioBtn.setVisibility(View.VISIBLE);
                radioBtn.setContent(mBean.getBrokeNews().getAudioDuration());
                radioBtn.setTag(mBean);
                radioBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final ScoopButton voiceButton = (ScoopButton) v;
                        ScoopListBean t = (ScoopListBean) v.getTag();

                        //停止视频播放
                        GSYVideoManager.releaseAllVideos();
                        final MediaManager me = MediaManager.getIntance();
                        if (me.isPlay()) {
                            //停止播放语音
                            me.release();
                            //停止动画
                            me.getTextView().endAnimation();

                            //恢复时间
                            me.getTextView().setContent(me.getContentBean().getBrokeNews().getAudioDuration());

                            if (me.getContentBean().getBrokeNews().getId() == t.getBrokeNews().getId()) {
                                return;
                            }
                        }

                        //播放动画
                        voiceButton.startAnimation();
                        //添加
                        me.setContentBean(t);
                        me.setTextView(voiceButton);
                        me.setOnProgressListener(new MediaManager.OnProgressListener() {
                            @Override
                            public void Onprogress(final ScoopButton te, final String pro) {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        myVoiceButton = te;
                                        text = pro;
                                        mHandler.sendEmptyMessage(0);
                                    }
                                }).start();
                            }
                        });

                        //播放音频
                        me.playSound(mBean.getBrokeNews().getUrl(), new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                me.getTextView().endAnimation();
                            }
                        });
                    }

                });
                break;
            default:
                break;
        }

    }


    /**
     * 出错
     *
     * @param msg
     */
    @Override
    public void setError(String msg) {
        layoutMask.setReloadButtonText("点击重试~~");
        layoutMask.setStatus(LoadingLayout.Error);
        layoutMask.setErrorText(msg);
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void setNetError(String msg) {
        layoutMask.setReloadButtonText("点击重试~~");
        layoutMask.setStatus(LoadingLayout.No_Network);
        layoutMask.setNoNetworkText(msg);
    }

    /**
     * 关注成功
     */
    @Override
    public void addSuccess() {
        follows++;
        setChecked(follows);
        mBean.setIsAttention(1);
        mBean.setAttention(follows);
        BusFactory.getBus().post(new Event.refreshMessage(mBean));
        likeButtonEnable = true;
    }

    /**
     * 关注失败
     *
     * @param msg
     */
    @Override
    public void addError(String msg) {
        Toasty.normal(this, msg).show();
        setNormal(follows);
        likeButtonEnable = true;
    }

    /**
     * 取关成功
     */
    @Override
    public void cancelSuccess() {
        follows--;
        setNormal(follows);
        mBean.setIsAttention(0);
        mBean.setAttention(follows);
        BusFactory.getBus().post(new Event.refreshMessage(mBean));
        likeButtonEnable = true;
    }

    /**
     * 取关失败
     *
     * @param msg
     */
    @Override
    public void cancelError(String msg) {
        Toasty.normal(this, msg).show();
        setChecked(follows);
        likeButtonEnable = true;
    }

    /**
     * 设置关注状态
     */
    private void setChecked(int num) {
        likeButton.setLiked(true);
        attentionNum.setTextColor(getResources().getColor(R.color.global_base));
        attentionNum.setText(StringUtils.transformNum(num + "") + "人关注");//设置关注人数
        likeButton.setEnabled(true);
    }

    /**
     * 设置未关注状态
     */
    private void setNormal(int num) {
        likeButton.setLiked(false);
        attentionNum.setTextColor(getResources().getColor(R.color.global_gray_lv2));
        attentionNum.setText(StringUtils.transformNum(num + "") + "人关注");//设置关注人数
        likeButton.setEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("内容详情");
        MobclickAgent.onResume(this);
        ActionLogUtils.getInstance().onResume(this, ActionConstant.SCOOPDETAIL);
    }


    @Override
    protected void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("内容详情");
        MobclickAgent.onPause(this);
        MediaManager.getIntance().release();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.SCOOPDETAIL);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BusFactory.getBus().unregister(this);
    }


    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }

    /**
     * eventBus 接收器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            if (event.isLogin()) {//登录
                mPresenter.getDetail(brokeId + "");
            } else {//注销
                mPresenter.getDetail(brokeId + "");
            }
        }
    }

    private Handler mHandler = new MyHandler(this);

    private static class MyHandler extends Handler {
        private final WeakReference<ScoopDetailActivity> mActivity;

        public MyHandler(ScoopDetailActivity activity) {
            mActivity = new WeakReference<ScoopDetailActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ScoopDetailActivity scoop = mActivity.get();
            switch (msg.what) {
                case 0:
                    scoop.myVoiceButton.setContent(scoop.text);
                    break;
                default:
                    break;
            }
        }


    }


}
